/*
 * Copyright (C) 2006-2007 Eskil Bylund
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

using System;

using Gtk;
using Glade;
using Mono.Unix;

using DCSharp.Backend.Connections;
using DCSharp.Backend.Managers;
using DCSharp.Backend.Objects;
using DCSharp.Xml;

using Column = DCSharp.Gui.FileListStore.Column;

namespace DCSharp.Gui
{
	public class FileListPage : Page
	{
		private const int DisableSortingLimit = 100;

		private FileListStore fileStore;
		private FileListView fileView;

		private ActionGroup actionGroup;

		#region Constructors

		public FileListPage(User user, FileList fileList)
		{
			if (user == null)
			{
				throw new ArgumentNullException("user");
			}

			ScrolledWindow scrolledWindow = new ScrolledWindow();
			scrolledWindow.ShadowType = ShadowType.In;
			PackEnd(scrolledWindow, true, true, 0);

			// User interface
			ActionEntry[] entries = new ActionEntry[] {
				new ActionEntry("VisibleColumns", null, Catalog.GetString("_Visible Columns..."), null,
					Catalog.GetString("Edit visible columns"),
					null),
			};

			actionGroup = new ActionGroup("FileListingPageActions");
			actionGroup.Add(entries);

			// Model
			fileStore = new FileListStore(fileList);
			fileStore.SetSortFunc((int)Column.Name, FileSortFunc);
			fileStore.SetSortColumnId((int)Column.Name, SortType.Ascending);

			// View
			fileView = new FileListView(fileStore, user);
			fileView.RowExpanded += OnRowExpanded;
			fileView.GetColumn("TTH").Visible = false;

			scrolledWindow.Add(fileView);
			scrolledWindow.ShowAll();

			// Visible columns
			VisibleColumnsWindow.ConnectToWidget(this, actionGroup["VisibleColumns"],
				fileView.Columns, fileView.Columns[0]);
		}

		#endregion

		#region Properties

		public override string Title
		{
			get { return fileView.User.Nick; }
		}

		public override Gdk.Pixbuf Icon
		{
			get { return this.RenderIcon(Stock.Directory, IconSize.Menu, null); }
		}

		public override string Tooltip
		{
			get { return null; }
		}

		public override ActionGroup Actions
		{
			get { return actionGroup; }
		}

		public int VisibleColumns
		{
			get { return Util.GetVisibleColumns(fileView.Columns); }
			set { Util.SetVisibleColumns(fileView.Columns, value | 1); }
		}

		public FileList FileList
		{
			get { return fileStore.FileList; }
			set
			{
				fileStore.FileList = value;
				OnPageChanged();
			}
		}

		public User User
		{
			get { return fileView.User; }
		}

		#endregion

		#region Methods

		public void SelectPath(string path)
		{
			if (path == null)
			{
				throw new ArgumentNullException("path");
			}

			path = path.Replace('\\', System.IO.Path.DirectorySeparatorChar);
			path = path.Replace(System.IO.Path.AltDirectorySeparatorChar,
				System.IO.Path.DirectorySeparatorChar);

			if (FileList != null)
			{
				TreePath treePath = fileView.ExpandToPathString(path);
				if (treePath != null)
				{
					fileView.Selection.SelectPath(treePath);
					fileView.ScrollToCell(treePath, null, true, 0.5F, 0);
				}
			}
		}

		protected override void OnDestroyed()
		{
			fileStore.FileList = null;
			base.OnDestroyed();
		}

		private int FileSortFunc(TreeModel model, TreeIter tia, TreeIter tib)
		{
			object obja = model.GetValue(tia, (int)Column.Object);
			object objb = model.GetValue(tib, (int)Column.Object);

			if (obja is DirectoryNode && objb is FileNode)
			{
				return -1;
			}
			if (obja is FileNode && objb is DirectoryNode)
			{
				return 1;
			}

			string namea = model.GetValue(tia, (int)Column.Name) as string;
			string nameb = model.GetValue(tib, (int)Column.Name) as string;

			return String.Compare(namea, nameb);
		}

		private void OnRowExpanded(object obj, RowExpandedArgs args)
		{
			TreeIter iter;
			if (fileStore.GetIter(out iter, args.Path))
			{
				bool loaded = (bool)fileStore.GetValue(iter, (int)Column.Loaded);
				DirectoryNode directory = fileStore.GetValue(iter,
					(int)Column.Object) as DirectoryNode;

				if (loaded || directory == null)
				{
					return;
				}

				bool disableSorting = directory.Directories.Count + directory.Files.Count >
					DisableSortingLimit;

				int sortColumnId;
				SortType sortOrder;
				if (disableSorting && fileStore.GetSortColumnId(out sortColumnId,
					out sortOrder))
				{
					fileStore.SetSortColumnId(-2, SortType.Ascending);
					fileStore.Load(iter);
					fileStore.SetSortColumnId(sortColumnId, sortOrder);
				}
				else
				{
					fileStore.Load(iter);
				}
			}
		}

		#endregion
	}
}
